<template>
  <div class="design-history">
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <h2>历史记录</h2>
          <div class="header-controls">
            <span class="page-info">第 {{ currentPage }} 页 / 每页15条 / 共 {{ total }} 条</span>
            <div class="custom-pagination">
              <el-button
                  size="small"
                  :disabled="currentPage <= 1"
                  @click="jumpToPage(currentPage - 1)"
              >
                上一页
              </el-button>
              <span class="page-number">{{ currentPage }}</span>
              <el-button
                  size="small"
                  :disabled="currentPage >= Math.ceil(total / 15)"
                  @click="jumpToPage(currentPage + 1)"
              >
                下一页
              </el-button>
            </div>
            <el-button type="primary" @click="fetchHistoryRecords" :loading="loading">刷新</el-button>
          </div>
        </div>
      </template>
      <div class="history-list" v-loading="loading">
        <div v-if="historyRecords.length === 0 && !loading" class="empty-tip">
          <p>暂无历史记录</p>
          <template v-if="!isUserLoggedIn">
            <p class="login-tip">登录后才能查看和管理您的教学计划历史记录</p>
            <el-button type="primary" size="small" @click="goToLogin">立即登录</el-button>
          </template>
          <template v-else>
            <p class="create-tip">您可以在"开始设计"页面创建新的教学计划</p>
            <el-button type="primary" size="small" @click="goToCreate">开始设计</el-button>
          </template>
        </div>
        <div v-for="(record, index) in historyRecords"
             :key="index"
             class="history-item"
             @click="viewHistoryDetail(record)">
          <div class="history-item-header">
            <span class="history-subject">【{{ record.subject }}】{{ record.grade }}</span>
            <span class="history-time">{{ record.time }}</span>
          </div>
          <div class="history-content">{{ record.content }}</div>
          <div class="history-item-footer">
            <el-tag size="small" type="info">
              {{ record.duration }}分钟
            </el-tag>
            <span class="topic-tag">{{ record.title }}</span>
          </div>
        </div>
        <div class="bottom-space"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import request from '@/utils/request'

const historyRecords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

// 使用计算属性检查登录状态
const isUserLoggedIn = computed(() => {
  const token = localStorage.getItem('token')
  const teacherId = localStorage.getItem('teacherId')
  return !!(token && teacherId)
})

// 添加全局样式
const globalStyle = document.createElement('style');
globalStyle.textContent = `
.teaching-plan-detail-dialog .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
.teaching-plan-detail-dialog .el-message-box {
  width: 80%;
  max-width: 800px;
}
.teaching-plan-detail-dialog .el-message-box__message p {
  margin: 0;
  line-height: 1.6;
}
.teaching-plan-detail-dialog .el-message-box__message div {
  margin-bottom: 10px;
}
.teaching-plan-detail-dialog .el-message-box__message div[style*="white-space: pre-wrap;"] {
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
  max-height: 300px;
  overflow-y: auto;
}
`;
document.head.appendChild(globalStyle);

// 直接跳转到指定页面
const jumpToPage = (page) => {
  console.log('跳转到页面:', page)
  if (page < 1 || page > Math.ceil(total.value / 15)) {
    console.log('页码超出范围，忽略')
    return
  }

  if (page === currentPage.value) {
    console.log('当前已是第', page, '页，忽略')
    return
  }

  // 更新页码
  currentPage.value = page

  // 显示加载中
  loading.value = true
  historyRecords.value = []

  // 显示提示
  ElMessage.info({
    message: `正在加载第${page}页数据...`,
    duration: 1000
  })

  // 调用获取数据
  fetchHistoryRecordsForPage(page)
}

// 为特定页面获取历史记录
const fetchHistoryRecordsForPage = async (page) => {
  loading.value = true
  historyRecords.value = []

  // 先检查用户是否登录
  if (!isUserLoggedIn.value) {
    ElMessage.warning('您尚未登录，请先登录后查看个人历史记录')
    loading.value = false
    return
  }

  try {
    // 直接使用原始axios请求，避免可能的缓存问题
    const timestamp = new Date().getTime()
    const teacherId = localStorage.getItem('teacherId')
    console.log('正在使用teacherId:', teacherId, '请求历史记录')

    const response = await request({
      url: `/api/teaching-plans?_t=${timestamp}`,
      method: 'get',
      params: {
        teacherId: teacherId,
        page: page - 1, // 后端分页从0开始，前端从1开始
        size: 15
      }
    })

    console.log(`获取第${page}页数据响应:`, response)

    // 处理响应
    if (response.data && Array.isArray(response.data)) {
      historyRecords.value = response.data.map(item => ({
        id: item.id,
        subject: item.subject || '未指定',
        grade: item.grade || '未指定',
        title: item.title || '未命名教学计划',
        content: item.content ? (item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content) : '无内容',
        objectives: item.objectives || '',
        activities: item.activities || '',
        resources: item.resources || '',
        assessment: item.assessment || '',
        duration: item.duration || 45,
        teacherId: item.teacherId,
        time: new Date(item.createTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }))

      // 从响应头获取总记录数
      const totalCount = response.headers['x-total-count']
      console.log('从响应头获取总记录数:', totalCount)
      total.value = totalCount ? parseInt(totalCount) : historyRecords.value.length

      // 如果数据为空，显示提示
      if (historyRecords.value.length === 0) {
        ElMessage.info('暂无历史教学计划记录，请先创建教学计划')
      }
    } else {
      console.error('响应格式不正确:', response)
      ElMessage.error('获取数据失败：格式不正确')
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)

    // 检查是否是认证错误
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录后再查看历史记录')
      // 清除可能过期的token和teacherId
      localStorage.removeItem('token')
      localStorage.removeItem('teacherId')

      // 提示用户登录
      setTimeout(() => {
        if (confirm('您需要重新登录，是否立即前往登录页面？')) {
          window.location.href = '/login'
        }
      }, 1000)
    } else {
      ElMessage.error('获取历史记录失败: ' + (error.message || '未知错误'))
    }
  } finally {
    loading.value = false
  }
}

// 查看历史记录详情
const viewHistoryDetail = (item) => {
  // 处理内容展示
  const contentHtml = item.content ? `<div style="white-space: pre-wrap;">${item.content}</div>` : '无内容';
  const objectivesHtml = item.objectives ? `<div style="white-space: pre-wrap;">${item.objectives}</div>` : '无详细教学目标';
  const activitiesHtml = item.activities ? `<div style="white-space: pre-wrap;">${item.activities}</div>` : '无详细教学活动';
  const resourcesHtml = item.resources ? `<div style="white-space: pre-wrap;">${item.resources}</div>` : '无教学资源';
  const assessmentHtml = item.assessment ? `<div style="white-space: pre-wrap;">${item.assessment}</div>` : '无评估方式';

  ElMessageBox.alert(
      `<div style="font-size:15px;line-height:1.6;">
      <div style="margin-bottom:15px;"><strong>标题：</strong>${item.title}</div>
      <div style="margin-bottom:15px;"><strong>教学目标：</strong>${objectivesHtml}</div>
      <div style="margin-bottom:15px;"><strong>教学活动：</strong>${activitiesHtml}</div>
      <div style="margin-bottom:15px;"><strong>教学资源：</strong>${resourcesHtml}</div>
      <div style="margin-bottom:15px;"><strong>评估方式：</strong>${assessmentHtml}</div>
      <div style="margin-bottom:15px;"><strong>详细内容：</strong>${contentHtml}</div>
      <div style="margin-bottom:8px;"><strong>科目：</strong>${item.subject}</div>
      <div style="margin-bottom:8px;"><strong>年级：</strong>${item.grade}</div>
      <div style="margin-bottom:8px;"><strong>课时：</strong>${item.duration}分钟</div>
      <div><strong>创建时间：</strong>${item.time}</div>
    </div>`,
      '教学计划详情',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭',
        customClass: 'teaching-plan-detail-dialog'
      }
  )
}

// 跳转到登录页面
const goToLogin = () => {
  window.location.href = '/login';
}

// 跳转到创建设计页面
const goToCreate = () => {
  window.location.href = '/design/new';
}

// 获取历史记录（默认获取第一页）
const fetchHistoryRecords = async () => {
  currentPage.value = 1
  fetchHistoryRecordsForPage(1)
}

onMounted(() => {
  // 检查登录状态
  if (!isUserLoggedIn.value) {
    ElMessage.warning({
      message: '您尚未登录或登录已过期，请先登录后查看个人历史记录',
      duration: 5000
    });
    return;
  }

  // 加载第一页历史记录数据
  fetchHistoryRecords();
})
</script>

<style scoped>
.design-history {
  height: 100%;
}

.history-card {
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

.history-list {
  height: calc(100vh - 190px);
  overflow-y: auto;
  padding: 10px 10px 25px 10px;
}

.history-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-item:last-child {
  margin-bottom: 30px; /* 为最后一项增加额外的底部边距 */
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-subject {
  font-weight: 600;
  color: #303133;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-content {
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.history-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topic-tag {
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 15px;
}

.empty-tip p {
  margin: 0;
}

.login-tip, .create-tip {
  color: #606266;
  font-size: 12px;
}

/* 添加滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.custom-pagination {
  display: flex;
  align-items: center;
}

.page-number {
  margin: 0 10px;
  color: #409EFF;
  font-weight: bold;
}

.page-info {
  color: #909399;
  font-size: 13px;
}

.bottom-space {
  height: 20px;
}
</style>